package com.example.myapplication;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Stack;

public class NoteContentActivity extends AppCompatActivity {
  Note currentNote;
  String userName;
  String userAccount;

  boolean isTyping=false;
  boolean isUndoOrder = false;
  boolean isRedoOrder = false;
  boolean needToSave = false;
  //boolean isFavour;
  boolean isInitOrder=false;
  NoteDataBaseHelper noteDataBaseHelper;

  ImageButton backButton;
  ImageButton shareButton;
  ImageButton exportButton;
  ImageButton favourButton;
  ImageButton deleteButton;

  ImageButton redoButton;
  ImageButton undoButton;
  ImageButton finishButton;


  TextView dateText;
  TextView timeText;
  TextView wordNumberText;
  TextView classifyText;

  EditText noteTitleText;
  EditText noteContentText;

  LinearLayout dateLayout;
  LinearLayout shareLayout;

  LinearLayout controlLayout;
  LinearLayout finishLayout;
  FrameLayout buttonLayout;
  View inputArea;

  Stack<String> undoStack;
  Stack<String> redoStack;

  @Override protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.note_content_layout);

    Init();
    InitInfo();
    InitDeleteButton();
    InitFavourButton();
    InitShareButton();
    InitExportButton();

  }

  private void InitExportButton() {
    exportButton.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        //ExportTxtFile();

        Toast.makeText(NoteContentActivity.this, "导出txt文件成功", Toast.LENGTH_SHORT).show();
      }
    });
  }

  private void ExportTxtFile() {

  }

  private void InitShareButton() {
    shareButton.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        //ShowSharePanel();
        SharePanel();

      }
    });
  }

  private void SharePanel() {
    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setType("text/plain");
    intent.putExtra(Intent.EXTRA_TEXT,
        "标题:"
            + currentNote.getNoteTitle()
            + "\n内容:\n"
            + currentNote.getNoteContent()
            + "\n创建于" + currentNote.getCreateTime() + "\n");
    startActivity(Intent.createChooser(intent, "分享到..."));

  }

  private void ShowSharePanel() {
    Dialog dialog = new Dialog(this);
    dialog.setContentView(R.layout.shared_menu_window);
    LinearLayout qqShareLayout = dialog.findViewById(R.id.qq_share_layout);
    LinearLayout wechatShareLayout = dialog.findViewById(R.id.wechat_shared_layout);
    LinearLayout blogShareLayout = dialog.findViewById(R.id.blog_shared_layout);
    qqShareLayout.setOnTouchListener(new View.OnTouchListener() {
      @Override public boolean onTouch(View v, MotionEvent event) {
        Toast.makeText(NoteContentActivity.this, "qq分享", Toast.LENGTH_SHORT).show();
        return true;
      }
    });


    dialog.show();
  }

  private void InitFavourButton() {
    favourButton.setImageResource(currentNote.isFavour() ? R.drawable.favour_start_favoured
        : R.drawable.favour_start_unfavour);
    favourButton.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {

        currentNote.setFavour(!currentNote.isFavour());
        favourButton.setImageResource(currentNote.isFavour() ? R.drawable.favour_start_favoured
            : R.drawable.favour_start_unfavour);
        noteDataBaseHelper.Open();
        noteDataBaseHelper.UpdateNoteFavour(currentNote);
        noteDataBaseHelper.Close();

      }
    });
  }

  private void InitDeleteButton() {
    deleteButton.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {

        Dialog dialog = new Dialog(v.getContext());
        dialog.setContentView(R.layout.dialog_delete_window);
        Button positiveButton = dialog.findViewById(R.id.positive_button);
        positiveButton.setOnClickListener(new View.OnClickListener() {
          @Override public void onClick(View v) {
            //删除操作
            noteDataBaseHelper.Open();
            noteDataBaseHelper.DeleteSingleNoteByID(currentNote.getNoteId());
            noteDataBaseHelper.Close();
            finish();
          }
        });
        Button negativeButton = dialog.findViewById(R.id.negative_button);
        negativeButton.setOnClickListener(new View.OnClickListener() {
          @Override public void onClick(View v) {
            dialog.dismiss();
          }
        });
        Window window = dialog.getWindow();
        if (window != null) {
          window.setGravity(Gravity.BOTTOM);

        }
        dialog.show();
      }
    });
  }

  private void InitInfo() {

    SetDateTip();

    SetNoteInfo();
    SetWordCount(currentNote.getNoteContent().length());

  }

  private void SetNoteInfo() {
    isInitOrder = true;
    noteTitleText.setText(currentNote.getNoteTitle());

    noteContentText.setText(currentNote.getNoteContent());
    isInitOrder = false;

  }

  private void SetDateTip() {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(currentNote.getCreateTime());
    int year = calendar.get(Calendar.YEAR);
    int month = calendar.get(Calendar.MONTH)+1;
    int day = calendar.get(Calendar.DAY_OF_MONTH);

    int hour = calendar.get(Calendar.HOUR);
    int minute = calendar.get(Calendar.MINUTE);

    String dateStr = getString(R.string.note_date, String.valueOf(year), String.valueOf(month),
        String.valueOf(day));
    String timeStr = getString(R.string.note_time,String.valueOf(hour),String.valueOf(minute));

    dateText.setText(dateStr);
    timeText.setText(timeStr);

  }

  private void SetWordCount(int number) {
    wordNumberText.setText(getString(R.string.note_word_number, String.valueOf(number)));



  }

  private void Init() {
    Bundle bundle = getIntent().getExtras();
    userName = bundle.getString("userName");
    userAccount = bundle.getString("userAccount");
    currentNote = (Note) bundle.getSerializable("currentNote");
    //isFavour = currentNote.isFavour();
    noteDataBaseHelper = new NoteDataBaseHelper(this);

    undoStack = new Stack<>();

    redoStack = new Stack<>();


    backButton = findViewById(R.id.back_button);
    shareButton = findViewById(R.id.share_button);
    exportButton = findViewById(R.id.export_button);
    favourButton = findViewById(R.id.favour_button);
    deleteButton = findViewById(R.id.delete_button);
    redoButton = findViewById(R.id.redo_button);
    undoButton = findViewById(R.id.undo_button);
    finishButton = findViewById(R.id.finish_button);

    buttonLayout = findViewById(R.id.button_layout);
    dateText = findViewById(R.id.date_info);
    timeText = findViewById(R.id.time_info);
    wordNumberText = findViewById(R.id.note_word_number_tip);
    classifyText = findViewById(R.id.classify_info);

    noteTitleText = findViewById(R.id.note_title_text);
    noteContentText = findViewById(R.id.note_content_text);

    dateLayout = findViewById(R.id.date_layout);
    shareLayout = findViewById(R.id.share_layout);
    controlLayout = findViewById(R.id.control_layout);
    controlLayout.setVisibility(View.INVISIBLE);
    finishLayout = findViewById(R.id.finish_layout);
    finishLayout.setVisibility(View.INVISIBLE);

    inputArea = findViewById(R.id.input_area);

    backButton.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        if (needToSave == false) {
          finish();
          return;
        }

        Dialog dialog = new Dialog(v.getContext());
        dialog.setContentView(R.layout.dialog_save_window);
        Button positiveButton = dialog.findViewById(R.id.positive_button);
        positiveButton.setOnClickListener(new View.OnClickListener() {
          @Override public void onClick(View v) {
            //确认保存
            SaveNoteData();
            finish();
          }
        });
        Button negativeButton = dialog.findViewById(R.id.negative_button);
        negativeButton.setOnClickListener(new View.OnClickListener() {
          @Override public void onClick(View v) {
            dialog.dismiss();
          }
        });
        Window window = dialog.getWindow();
        if (window != null) {
          window.setGravity(Gravity.BOTTOM);

        }
        dialog.show();
      }

    });

    noteTitleText.setOnTouchListener(new View.OnTouchListener() {
      @Override public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
          SetTypingMod();
        }
        return false;
      }
    });
    noteTitleText.addTextChangedListener(new TextWatcher() {
      @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {

      }

      @Override public void onTextChanged(CharSequence s, int start, int before, int count) {

      }

      @Override public void afterTextChanged(Editable s) {
        if (!isInitOrder) {
          needToSave = true;
        }
      }
    });
    noteContentText.setOnTouchListener(new View.OnTouchListener() {
      @Override public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
          SetTypingMod();
        }
        return false;
      }
    });
    inputArea.setOnTouchListener(new View.OnTouchListener() {
      @Override public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
          isTyping = true;
          noteContentText.requestFocus();
          InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
          imm.showSoftInput(noteContentText, InputMethodManager.SHOW_IMPLICIT);
          SetTypingMod();
        }
        return false;
      }
    });
    finishButton.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        isTyping = false;
        needToSave = false;
        InputMethodManager inputMethodManager =
            (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        //隐藏软键盘
        inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), 0);

        SetViewMod();
        ClearUndoStack();
        ClearRedoStack();
        CheckTitle();
        SaveNoteData();


      }
    });
    noteContentText.addTextChangedListener(new TextWatcher() {
      @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        if (!isUndoOrder && !isRedoOrder && !isInitOrder) {
          needToSave = true;
          SaveTextToUnDoStack(s.toString());
          ClearRedoStack();
        }

      }

      @Override public void onTextChanged(CharSequence s, int start, int before, int count) {

      }

      @Override public void afterTextChanged(Editable s) {
        int wordCount = s.toString().length();
        SetWordCount(wordCount);

        //String cacheString = s.toString();
        //SaveTextToUnDoStack(cacheString);
        //ClearRedoStack();
      }
    });

    undoButton.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {

        UndoText();


      }
    });
    redoButton.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        RedoText();
      }
    });

  }

  private void SaveNoteData() {
    currentNote.setNoteTitle(noteTitleText.getText().toString());
    currentNote.setNoteContent(noteContentText.getText().toString());
    //currentNote.setFavour(isFavour);

    Date newDate=new Date();
    SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String outputDateStr = outputFormat.format(newDate);
    try {
      Date currentDate=outputFormat.parse(outputDateStr);
      currentNote.setUpdateTime(currentDate);
    } catch (ParseException e) {
      throw new RuntimeException(e);
    }

    noteDataBaseHelper.Open();
    int number=0;
    if (currentNote.getNoteId() == -1) {
      number=noteDataBaseHelper.InsertSingleNote(currentNote);
    } else {
      number=noteDataBaseHelper.UpdateNoteByID(currentNote);
    }
    noteDataBaseHelper.Close();

    if (number == 1) {
      Toast.makeText(this, "保存笔记成功...", Toast.LENGTH_SHORT).show();
    } else {
      Toast.makeText(this, "服务器出小差了...", Toast.LENGTH_SHORT).show();
    }
  }

  private void ClearRedoStack() {

    redoStack.clear();
    redoButton.setColorFilter(null);
  }
  private void ClearUndoStack() {

    undoStack.clear();
    undoButton.clearColorFilter();
  }

  private void SaveTextToUnDoStack(String cacheString) {
    undoStack.push(cacheString);
    undoButton.setColorFilter(R.color.black);

  }
  private void UndoText() {
    if (undoStack.empty()) {
      return;
    }
    String previousText = undoStack.pop();
    isUndoOrder = true;
    //redoStack.push(previousText);
    redoButton.setColorFilter(R.color.black);
    redoStack.push(noteContentText.getText().toString());

    noteContentText.setText(previousText);
    isUndoOrder = false;
    if (undoStack.empty()) {
      undoButton.setColorFilter(null);
    }

  }
  private void RedoText() {
    if (redoStack.empty()) {
      return;
    }

    isRedoOrder = true;
    String nextText = redoStack.pop();
    //undoStack.push(nextText);
    undoStack.push(noteContentText.getText().toString());
    noteContentText.setText(nextText);
    isRedoOrder = false;
    undoButton.setColorFilter(R.color.black);

    if (redoStack.empty()) {
      redoButton.setColorFilter(null);
    }

  }

  private void CheckTitle() {
    if (noteTitleText.getText().toString() == null || noteTitleText.getText()
        .toString()
        .isEmpty()) {
      noteTitleText.setText("新笔记");

    }
  }

  private void SetTypingMod() {
    dateLayout.setVisibility(View.INVISIBLE);
    shareLayout.setVisibility(View.INVISIBLE);

    controlLayout.setVisibility(View.VISIBLE);
    finishLayout.setVisibility(View.VISIBLE);
    isTyping = true;
  }
  private void SetViewMod() {
    controlLayout.setVisibility(View.INVISIBLE);
    finishLayout.setVisibility(View.INVISIBLE);

    dateLayout.setVisibility(View.VISIBLE);
    shareLayout.setVisibility(View.VISIBLE);
    isTyping = false;
    noteTitleText.clearFocus();
    noteContentText.clearFocus();
  }
}
